using System;
using System.Collections.Generic;
using System.Text;

namespace LeisureCenter.Api.Tools
{
    public class DisposableList<T> : List<T>, IDisposable
    {
        protected bool disposed = false;

        ~DisposableList()
        {
            Dispose(false);
        }

        #region IDisposable Membres

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                DisposeItems();
                disposed = true;
            }
        }

        protected void DisposeIfApplicable(T item)
        {
            if (item is IDisposable)
            {
                ((IDisposable)item).Dispose();
            }
        }

        #region reintroduced members of List<T>

        public new void Clear()
        {
            DisposeItems();
            base.Clear();
        }

        private void DisposeItems()
        {
            this.ForEach(DisposeIfApplicable);
        }

        public new bool Remove(T item)
        {
            int index = this.IndexOf(item);
            if (index >= 0)
            {
                DisposeIfApplicable(item);
            }
            return base.Remove(item);
        }

        public new void RemoveAt(int index)
        {
            if (index < this.Count)
            {
                DisposeIfApplicable(this[index]);
            }
            base.RemoveAt(index);
        }

        public new void RemoveRange(int index, int count)
        {
            GetRange(index, count).ForEach(DisposeIfApplicable);
            base.RemoveRange(index, count);
        }

        #endregion
    }
}
